package com.hpq.user.service.adapter;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.hpq.common.domain.enums.YesOrNoEnum;
import com.hpq.user.domain.model.ItemBag;
import com.hpq.user.domain.model.User;
import com.hpq.user.domain.model.UserBackpack;
import com.hpq.user.domain.vo.response.user.UserBadgesResp;
import com.hpq.user.domain.vo.response.user.UserInfoResp;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import org.springframework.beans.BeanUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户适配器
 */
@Slf4j
public class UserAdapter {
    /**
     * 构建用户详情VO
     * @param userInfo
     * @param modifyNameChance
     * @return
     */
    public static UserInfoResp buildUserInfoResp(User userInfo, Integer modifyNameChance) {
        UserInfoResp userInfoResp = new UserInfoResp();
        BeanUtils.copyProperties(userInfo, userInfoResp);
        userInfoResp.setModifyNameChance(modifyNameChance);
        return userInfoResp;
    }

    public static User buildUserSave(String openId) {
        return User.builder().openId(openId).build();
    }

    public static User buildAuthorizeUser(Long uid, WxOAuth2UserInfo userInfo) {
        User user = new User();
        user.setId(uid);
        user.setAvatar(userInfo.getHeadImgUrl());
        user.setName(userInfo.getNickname());
        user.setSex(userInfo.getSex());
        if (userInfo.getNickname().length() > 6) {
            user.setName("名字过长" + RandomUtil.randomInt(100000));
        } else {
            user.setName(userInfo.getNickname());
        }
        return user;

    }

    /**
     *  构建用户徽章列表
     * @param itemBags
     * @param userBadges
     * @param user
     * @return
     */
    public static List<UserBadgesResp> buildUserBadgesResp(List<ItemBag> itemBags, List<UserBackpack> userBadges, User user) {
        if (ObjectUtil.isNull(user)) {
            // 这里 user 入参可能为空，防止 NPE 问题
            return Collections.emptyList();
        }
        // 获取用户所有徽章
        Set<Long> itemIdSet = userBadges.stream().map(UserBackpack::getItemId).collect(Collectors.toSet());
        return itemBags.stream().map(a -> {
                    UserBadgesResp resp = new UserBadgesResp();
                    BeanUtil.copyProperties(a, resp);
                    resp.setObtain(itemIdSet.contains(a.getId()) ? YesOrNoEnum.YES.getStatus() : YesOrNoEnum.NO.getStatus());
                    resp.setWearing(ObjectUtil.equal(a.getId(), user.getItemId()) ? YesOrNoEnum.YES.getStatus() : YesOrNoEnum.NO.getStatus());
                    return resp;
                }).sorted(Comparator.comparing(UserBadgesResp::getWearing, Comparator.reverseOrder())
                        .thenComparing(UserBadgesResp::getObtain, Comparator.reverseOrder()))
                .collect(Collectors.toList());
    }
}
